#!/usr/bin/python
#
#       evolution_data mail.py Version 0.1
#
#       Copyright 2008 David Konsumer <david.konsumer@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

# Check mail from Evolution-setup accounts, directly (not using evolution)

import gconf
from xml.dom.minidom import parseString
from urllib import unquote
import re
import imaplib

# not implemented yet...
#import poplib

class EvolutionMail:
	accounts={}
	
	def __init__(self):
		pass
	
	# parse acocunt info, and put it in the self.accounts array
	def update_accounts(self):
		self.accounts = {}
		client = gconf.client_get_default()
		accounts_x = client.get_list('/apps/evolution/mail/accounts', gconf.VALUE_STRING)
		ra = re.compile(r'([a-z]+)://([\w\-\.@]+)/')
		for ax in accounts_x:
			a={}
			doc = parseString(ax)
			account_data=str(doc.getElementsByTagName('source')[0].firstChild.firstChild.data).split(';')
			a['name'] = unquote(str(doc.firstChild.attributes['name'].value))
			for item in account_data:
				item=unquote(item).split('=')
				if len(item) == 2:
					a[item[0]] = item[1]
				elif len(item) > 1:
					a[item[0]] = item[1:]
				else:
					email_check = ra.findall(item[0])
					if len(email_check) > 0:
						a['protocol']=email_check[0][0]
						# this allows for account names that have @, like google apps...
						s=email_check[0][1].split('@')
						a['server'] = s.pop()
						a['username']="@".join(list(s))
					else:
						a[item[0]] = True
			
			self.accounts[a['name']] = a
	
	# check mail using account name and a password
	# only tested with gmail SSL imap servers
	# I am willing to add support for other types of evolution-supported
	# servers, if there is a need.
	#
	# I only use gmail, so this worked for me.
	#
	# if you find a server that doesn't work, send me more info: david.konsumer@gmail.com
	# you really should include UID in your IMAP search, or bad things will happen...
	def check_mail(self, account_name, password, search='(UID BODY[HEADER.FIELDS (SUBJECT FROM DATE)])', force_update=False):
		# update list, if it's empty, or force is turned on
		if not len(self.accounts) or force_update:
			self.update_accounts()
		
		# raises an exception if this soesn't exist...
		account = self.accounts[account_name]
		
		# hmm, not using this, looks like it might be useful, though...
		# account['command'] = account['command'].replace('%u', account['username']).replace('%h',account['server'])
		
		out = {}
		
		if account['protocol'] == 'imap':
			if account['use_ssl']=='always':
				mail = imaplib.IMAP4_SSL(account['server'])
			else:
				mail = imaplib.IMAP4(account['server'])
			
			ure  =re.compile('.UID ([0-9]+) ')
			
			mail.login(account['username'], password)
			mail.select('INBOX', readonly=True)
			r, data = mail.search(None, "(UNSEEN)")
			if len(data) ==1 and data[0] != '':
				ids=data[0].split(" ")
				for mid in ids:
					r, data = mail.fetch(mid, search)
					info = map(lambda x:x.split(': '),data[0][1].strip().split("\r\n"))
					uid = ure.findall(data[0][0])[0]
					o={}
					for header in info:
						o[header[0].lower()]=header[1]
					out[uid]=o
					
					# get rid of quotes around name...
					out[uid]['from'] = out[uid]['from'].replace('"','')
				
		return out
		
		

if __name__ == '__main__':
	passwords={
	  'ACCOUNT_NAME1':'YER_PASSWORD',
	  'ACCOUNT_NAME2':'YER_PASSWORD2',
	}

	e = EvolutionMail()
	e.update_accounts()

	for account in e.accounts:
	  if passwords[account]:
		summary = e.check_mail(account, passwords[account])
		print "%d new messages in %s:" % (len(summary),account)
		if len(summary):
			for msg in summary:
				print summary[msg]
	
	

